package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.ChannelMapper;
import com.heima.admin.service.ChannelService;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.ChannelDTO;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @Author XHui
 * @Since 2024/2/2 18:47
 * @Version 1.0
 */
@Service
public class ChannelServiceImpl extends ServiceImpl<ChannelMapper, AdChannel> implements ChannelService {

    @Override
    public ResponseResult findByNameAndPage(ChannelDTO dto) {
        // 1.校验参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "请求参数为空");
        }
        // 检查并尝试矫正参数
        dto.checkParam();
        // 2.条件查询

        // 2.1 封装条件参数 name status ord 排序
        Page<AdChannel> pageReq = new Page<>(dto.getPage(), dto.getSize());
        // 构建支持lambda表达式的查询条件
        LambdaQueryWrapper<AdChannel> wrapper = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(dto.getName())) {
            wrapper.like(AdChannel::getName, dto.getName());
        }
        if (dto.getStatus() != null) {
            wrapper.like(AdChannel::getStatus, dto.getStatus());
        }
        // 排序
        wrapper.orderByAsc(AdChannel::getOrd);
        IPage<AdChannel> pageResult = this.page(pageReq, wrapper);
        // 3. 执行查询，封装返回结果
        return new PageResponseResult(
                dto.getPage(), dto.getSize(),
                pageResult.getTotal(), pageResult.getRecords()
        );
    }

    @Override
    public ResponseResult saveChannel(AdChannel channel) {
        // 1. 参数校验 name不为空 不能大于10个字符 不能重复
       /* if (StringUtils.isBlank(channel.getName())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "频道名称不能为空");
        }
        if (channel.getName().trim().length() > 10) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "频道名称应小于10个字符（左右空字符不计算在内）");
        }*/
        int count = this.count(Wrappers.<AdChannel>lambdaQuery().eq(AdChannel::getName, channel.getName()));
        if (count > 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "频道名称已存在");
        }
        // 2. 保存频道
        channel.setCreatedTime(new Date());
        boolean save = this.save(channel);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult update(AdChannel adChannel) {
        // 1. 校验参数, id
        if (adChannel.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "频道id不能为空");
        }
        AdChannel queriedChannelById = this.getById(adChannel.getId());
        // 1.1 校验待修改的频道是否存在
        if (queriedChannelById == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "频道不存在");
        }
        String channelName = adChannel.getName();
        // 频道名称不为空 && 不超过10个字符 && 不等于原来的频道名称
        if (StringUtils.isNotBlank(channelName) &&
                channelName.trim().length() <= 10 &&
                !channelName.equals(queriedChannelById.getName())) {
            int count = this.count(Wrappers.<AdChannel>lambdaQuery().eq(AdChannel::getName, channelName));
            if (count > 0) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "频道名称已存在");
            }
        }
        // 2. 更新频道
        updateById(adChannel);
        return ResponseResult.okResult();
    }

    /**
     * @param id 编号
     * @return 通用的结果返回类
     * @Transactional(rollbackFor = Exception.class)
     * 当Exception或其子类异常发生时，回滚事务
     * 按 ID 删除
     */

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult deleteById(Integer id) {
        // 1. 校验参数
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "频道id不能为空");
        }
        // 1. 根据id删除之前，状态必须是禁用状态: 0
        AdChannel queriedChannelById = this.getById(id);
        if (queriedChannelById == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "该频道不存在，删除失败");
        }
        if (queriedChannelById.getStatus()) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "频道已启用，无法删除 (请先禁用再删除)");
        }
        this.removeById(id);
        /*if (id > 45) {
            //throw new CustomException(AppHttpCodeEnum.PARAM_INVALID, "业务参数校验失败，id不能大于45");
            // 简写异常                                                                            工具类
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }*/
        return ResponseResult.okResult();
    }
}